﻿
using Newtonsoft.Json;
using System;

namespace UtilsBase
{
    public class UtilsObject
    {
        /// <summary>
        /// 将object对象转换为实体对象
        /// </summary>
        /// <typeparam name="T">实体对象类名</typeparam>
        /// <param name="asObject">object对象</param>
        /// <returns></returns>
        public static T ConvertObject<T>(object asObject) where T : new()
        {
            var json = JsonConvert.SerializeObject(asObject);
            return JsonConvert.DeserializeObject<T>(json);

            //var serializer = new JavaScriptSerializer();
            ////将object对象转换为json字符
            //var json = serializer.Serialize(asObject);
            ////将json字符转换为实体对象
            //var t = serializer.Deserialize<T>(json);
            //return t;
        }
        /// <summary>
        /// 动态对象转换为实体对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="o"></param>
        /// <returns></returns>
        public static T DynamicToEntity<T>(dynamic o)
        {
            string json = JsonConvert.SerializeObject(o, Settings);
            return JsonConvert.DeserializeObject<T>(json, Settings);
        }
        /// <summary>
        /// Json设置
        /// </summary>
        public static JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore,
            DateFormatString = "yyyy-MM-dd HH:mm",
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        };
    }
}
